package com.yeyaomai.dksns.flowis.servlet;

import java.io.StringWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisQueryOrder;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisStatDetailDTO;
import com.yeyaomai.dksns.flowis.service.FlowisQueryService;
import com.yeyaomai.dksns.flowis.servlet.dto.AjaxResult;

/**
 * @author dingtao@yeyaomai.com
 */
@Controller
@RequestMapping("/flowis/*")
public class FlowisQueryDetailController {

	private static Logger logger = LoggerFactory
			.getLogger(FlowisQueryDetailController.class);

	@Autowired
	FlowisQueryService flowisQueryService;

	private static ObjectMapper objectMapper = new ObjectMapper();

	@RequestMapping(value="query")
	public String flowisQuery(HttpServletRequest request,
			HttpServletResponse response, FlowisQueryOrder order,
			ModelMap modelMap) {

		order.addSort("access_date", Order.DESCENDING.toString());

		Page<FlowisStatDetailDTO> result = flowisQueryService.getSplit(order);

		modelMap.addAttribute("result", result);

		modelMap.addAttribute("order", order);

		return "visit-detail";

	}

	/**
	 * 
	 * 
	 * @param request
	 * @param response
	 * @param ip
	 * @return
	 */
	// TODO 前端 约定 json 数据格式
	@RequestMapping(value="ajax")
	@ResponseBody
	public String flowisQuery(HttpServletRequest request,
			HttpServletResponse response, String ip) {

		AjaxResult jsonresult = new AjaxResult();

		if (StringUtils.isBlank(ip)) {

			jsonresult.setResult(false);
		} else {

			// LinkedHashMap<String, String> queryArgs = new
			// LinkedHashMap<String, String>();
			// queryArgs.put("ip", ip);
			// TODO 查询mongodb 数据量大性能低 或者基于cookie
			// List<FlowisStatDetailDTO> dtos = flowisQueryService
			// .getDescbyCondition(queryArgs);

//			Cookie[] cookies = request.getCookies();
//			for (Cookie cookie : cookies) {
//
//			}

		}

		StringWriter sw = new StringWriter();
		try {
			objectMapper.writeValue(sw, jsonresult);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sw.toString();
	}

}
